'use strict';

var Kitui = (function() {
  function Kitui() {
    //如果页面上不存在require.js 则创建
    if (!_private.hasRequire()) {
      _private.createRequire();
    }
    this.states = {
      isConfig: false
    };
  };
  Kitui.fn = Kitui.prototype;
  /**
   * 预处理
   */
  Kitui.fn.ready = function(callback) {
    var i = setInterval(function() {
      if (_private.hasRequire()) {
        clearInterval(i);
        typeof callback === 'function' && callback();
      }
    }, 50);
  };
  /**
   * 全局配置
   */
  Kitui.fn.config = function(options) {
    var that = this;
    options = options || {};
    // 合并模块参数
    var mods = Object.assign(_private._mods(), options.paths);
    // require 配置模块路径
    require.config({
      //baseUrl: _private.getPath(),
      paths: mods
    });
    that.states.isConfig = true;
    return that;
  };
  /**
   * 加载模块
   */
  Kitui.fn.require = function(mods, callback) {
    if (!this.states.isConfig) {
      require.config({
        paths: _private._mods()
      });
      this.states.isConfig = true;
    }
    require(mods, callback);
  };
  /**
   *  定义模块
   */
  Kitui.fn.define = function(mods, callback) {
    if (typeof mods === 'function') {
      define(mods);
    } else {
      define(mods, callback);
    }
  };
  // 私用方法或者字段
  var _private = {
    /**
     * 检测require.js是否已加载
     */
    hasRequire: function() {
      return typeof require !== undefined && typeof require === 'function';
    },
    /**
     * 创建request.js
     */
    createRequire: function() {
      var that = this;
      var script = document.createElement('script');
      script.src = that.getPath() + 'lib/require.js';
      document.querySelector('head').appendChild(script);
    },
    /**
     * 获取框架目录
     */
    getPath: function() {
      var scripts = document.querySelectorAll('script');
      var path = '';
      for (var key in scripts) {
        if (scripts.hasOwnProperty(key)) {
          var src = scripts[key].src;
          if (src.search('kitui.js') !== -1) {
            var origin = location.origin;
            var t1 = src.substring(origin.length),
              t2 = t1.substr(0, t1.lastIndexOf('/') + 1);
            path = t2;
          }
        }
      }
      return path;
    },
    /**
     * 默认模块
     */
    _mods: function() {
      var that = this,
        _path = that.getPath();
      return {
        basic: _path + 'basic',
        dropdown: _path + 'dropdown',
        menu: _path + 'menu',
        message: _path + 'message',
        switch: _path + 'switch',
        jquery: _path + 'lib/jquery',
        modal: _path + 'modal'
      };
    }
  };
  return Kitui;
}());
// 添加到window对象
window.kitui = new Kitui();